package com.ks.core.api;

import com.ks.core.constant.Const;
import com.ks.core.core.Result;
import com.ks.core.core.ResultCode;
import com.ks.core.exception.GunsException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 签名校验
 *
 * @author kingdee
 */
@Aspect
@Component
public class SignValidAdvice {

    @Resource
    private SignValidUtil signValidUtil;

    @Pointcut("@annotation(com.kd.core.api.anno.SignValidate)")
    private void pointcut() {
    }

    @Around("pointcut() && args(..,bindingResult)")
    public Object around(ProceedingJoinPoint point, BindingResult bindingResult) throws Throwable {
        List<ObjectError> errorList = bindingResult.getAllErrors();
        if (!CollectionUtils.isEmpty(errorList)) {
            return Result.fail(new GunsException(ResultCode.FAIL.getCode(), errorList.stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.joining(", "))));
        }
        Object[] args = point.getArgs();
        ApiRequest request = ((ApiRequest) Arrays.stream(args).filter(arg -> arg instanceof ApiRequest)
                .findFirst().orElseGet(ApiRequest::new));
        String isSuccess = signValidUtil.check(request);
        if (!Const.SUCCESS_MESSAGE.equals(isSuccess)) {
            return Result.fail(new GunsException(ResultCode.FAIL.getCode(), isSuccess));
        }
        return point.proceed();
    }
}